﻿using FarmSmartSleep.Common.Domain.RBACFile;
using FarmSmartSleep.Common.Dtos;
using FarmSmartSleep.Common.Infrastructure;
using MediatR;
using Microsoft.EntityFrameworkCore;

namespace R.FarmSmartSleep.RBAC.API.Apliction.Command
{
    /// <summary>
    /// 登录
    /// </summary>
    public class LoginHandler : IRequestHandler<LoginCommon, ResultT<Employee>>
    {
        private readonly IBaseRepository<Employee> emploveeRep;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="emploveeRep"></param>
        public LoginHandler(IBaseRepository<Employee> emploveeRep)
        {
            this.emploveeRep = emploveeRep;
        }
        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<ResultT<Employee>> Handle(LoginCommon request, CancellationToken cancellationToken)
        {
            var Result = new ResultT<Employee>() { Code = (int)CodeEnum.success };
            try
            {
                var list = await emploveeRep.GetAll().FirstOrDefaultAsync(c=>c.Account==request.Account);
                 
                if (list == null)
                {;
                    Result.Messege = "账号不存在";
                    Result.Code = (int)CodeEnum.error;
                }
                else if(list.Password != request.Password)
                {
                    Result.Messege = "密码错误";
                    Result.Code = (int)CodeEnum.error;
                }
                else
                {
                    Result.Item = list;
                    Result.Messege = "登陆成功";
                }
                


            }
            catch (Exception)
            {
                Result.Code = (int)CodeEnum.error;
                Result.Messege = "登录异常";
                throw;
            }

            return Result;
        }
    }
}
